import json

# 自定义异常类
from json import JSONDecodeError


class GoodsNameError(Exception):
    def __init__(self, message="名称不存在！"):
        # 异常消息
        self.message = message
        # 调用父类构造函数
        super().__init__(self.message)


class GoodsAddRepeatError(Exception):
  def __init__(self, message="商品已存在，添加失败！"):
    self.message = message
    super().__init__(self.message)


class QuantityError(Exception):
  def __init__(self, message="商品数量格式输入错误，应为正整数！"):
    self.message = message
    super().__init__(self.message)


# json文件
json_path = "inventory.json"


# 添加新商品：向文件中添加新的商品记录。
def add_new_goods(inventory_list):
  goods_name = input("请输入要添加的商品名：")
  new_stock = input("请输入要添加的商品数量：")
  new_goods = {}
  # 捕获商品名称不存在的自定义异常。
  try:
    for i in range(len(inventory_list)):
      if goods_name == inventory_list[i]["goods_name"]:
        print("已添加过该商品，请勿重复添加！")
        # 捕获用户输入错误（如输入非数字时的类型异常）。
        raise GoodsAddRepeatError("您已添加过该商品！")
    new_goods["goods_name"] = goods_name
    new_goods["stock"] = new_stock
    inventory_list.append(new_goods)
    write_inventory_to_file(inventory_list)
    print(f"已成功添加【{goods_name}】，的库存【{new_stock}】件")
  except GoodsAddRepeatError as e:
    print(e)


# 展示库存列表
def show_inventory(inventory_list):
  print("-----商品名-------------------数量-----")
  for i in inventory_list:
    print(f"     {i['goods_name']}                     {i['stock']}     ")


# 查询商品库存：从文件中读取商品库存数据并展示。
def load_inventory():
  """
  从文件中读取商品库存数据并展示
  :return:
  """
  try:
    # 把json里的内容读到列表里
    with open(json_path, "r") as file:
      inventory_list = json.load(file)
      if file is not None:
        return inventory_list
  # 捕获文件读写错误。
  except FileNotFoundError:
    print("库存文件不存在，将自动创建......")
    with open(json_path, "w") as file:
      pass
    return []


# 修改商品库存：根据商品名称修改库存数量。
def modify_inventory(inventory_list):
  goods_name = input("请输入要修改库存的商品名：")
  new_stock = None
  new_goods = {}
  # 捕获商品名称不存在的自定义异常。
  try:
    for i in range(len(inventory_list)):
      if goods_name == inventory_list[i]["goods_name"]:
        new_stock = input("已在仓库中找到该商品，将库存数量修改为：")
        # 捕获用户输入错误（如输入非数字时的类型异常）。
        if not new_stock.isdigit():
          raise QuantityError("您输入的库存数量不是正整数，库存修改失败！")
      else:
        continue
      new_goods["goods_name"] = goods_name
      new_goods["stock"] = int(new_stock)
      inventory_list[i] = new_goods
      write_inventory_to_file(inventory_list)
      print(f"已成功将{goods_name}的库存修改为{new_stock}件")
      return inventory_list
    raise GoodsNameError("仓库中没有该商品，您需要先添加该商品！")
  except GoodsNameError as e:
    print(e)


# 向文件中写入商品库存
def write_inventory_to_file(inventory_list):
  try:
    with open(json_path, "w") as file:
      file.truncate(0)
      json.dump(inventory_list, file, ensure_ascii=False)
  except Exception("没有库存文件！") as e:
    print(f"没有此文件：{e}")


if __name__ == '__main__':
  # 定义一个大列表，里面套小字典
  # inventory_dict = []
  # with open(json_path, "w+") as file:
  #   json.dump(inventory_dict, file)
  while True:
    print("请选择操作：")
    print("1. 查询库存")
    print("2. 修改库存")
    print("3. 添加新商品")
    print("4. 退出系统")
    choice = input("请输入操作编号：")
    if choice == "1":
      show_inventory(load_inventory())
    elif choice == "2":
      pass
      modify_inventory(load_inventory())
    elif choice == "3":
      pass
      add_new_goods(load_inventory())
    elif choice == "4":
      exit()
    else:
      print("无效输入，请重新选择！")

























